<template>
  <el-dialog
    v-model="dialogVisible"
    :title="isEdit ? '编辑财务记录' : '新增财务记录'"
    width="600px"
    @close="handleClose"
  >
    <el-form
      ref="formRef"
      :model="form"
      :rules="formRules"
      label-width="100px"
    >
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="收支类型" prop="type">
            <el-select v-model="form.type" placeholder="请选择收支类型" style="width: 100%">
              <el-option label="收入" value="income" />
              <el-option label="支出" value="expense" />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="分类" prop="category">
            <el-select v-model="form.category" placeholder="请选择分类" style="width: 100%">
              <el-option label="律师费" value="lawyer_fee" />
              <el-option label="咨询费" value="consulting_fee" />
              <el-option label="办公费用" value="office_expense" />
              <el-option label="差旅费" value="travel_expense" />
              <el-option label="其他" value="other" />
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>
      
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="金额" prop="amount">
            <el-input-number
              v-model="form.amount"
              :min="0"
              :precision="2"
              placeholder="请输入金额"
              style="width: 100%"
            />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="日期" prop="date">
            <el-date-picker
              v-model="form.date"
              type="date"
              placeholder="请选择日期"
              style="width: 100%"
            />
          </el-form-item>
        </el-col>
      </el-row>
      
      <el-form-item label="描述" prop="description">
        <el-input
          v-model="form.description"
          type="textarea"
          :rows="3"
          placeholder="请输入描述"
        />
      </el-form-item>
      
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="关联案件" prop="caseId">
            <el-select
              v-model="form.caseId"
              placeholder="请选择关联案件"
              filterable
              clearable
              style="width: 100%"
            >
              <el-option
                v-for="caseItem in caseOptions"
                :key="caseItem.id"
                :label="caseItem.title"
                :value="caseItem.id"
              />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="关联合同" prop="contractId">
            <el-select
              v-model="form.contractId"
              placeholder="请选择关联合同"
              filterable
              clearable
              style="width: 100%"
            >
              <el-option
                v-for="contract in contractOptions"
                :key="contract.id"
                :label="contract.title"
                :value="contract.id"
              />
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="handleClose">取消</el-button>
        <el-button type="primary" :loading="loading" @click="handleSubmit">
          确定
        </el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
import { ref, reactive, computed, watch, onMounted } from 'vue'
import { ElMessage } from 'element-plus'
import type { FormInstance, FormRules } from 'element-plus'
import { createFinanceRecord, updateFinanceRecord } from '@/api/finance'
import { getCaseList } from '@/api/case'
import { getContractList } from '@/api/contract'
import type { FinanceRecord } from '@/types'

interface Props {
  visible: boolean
  formData: Partial<FinanceRecord>
}

interface Emits {
  (e: 'update:visible', value: boolean): void
  (e: 'success'): void
}

const props = defineProps<Props>()
const emit = defineEmits<Emits>()

const formRef = ref<FormInstance>()
const loading = ref(false)
const caseOptions = ref<any[]>([])
const contractOptions = ref<any[]>([])

const dialogVisible = computed({
  get: () => props.visible,
  set: (value) => emit('update:visible', value)
})

const isEdit = computed(() => !!props.formData.id)

const form = reactive<Partial<FinanceRecord>>({
  type: 'income',
  category: '',
  amount: undefined,
  description: '',
  date: '',
  caseId: '',
  contractId: ''
})

const formRules: FormRules = {
  type: [
    { required: true, message: '请选择收支类型', trigger: 'change' }
  ],
  category: [
    { required: true, message: '请选择分类', trigger: 'change' }
  ],
  amount: [
    { required: true, message: '请输入金额', trigger: 'blur' }
  ],
  description: [
    { required: true, message: '请输入描述', trigger: 'blur' }
  ],
  date: [
    { required: true, message: '请选择日期', trigger: 'change' }
  ]
}

// 监听表单数据变化
watch(
  () => props.formData,
  (newData) => {
    Object.assign(form, {
      type: 'income',
      category: '',
      amount: undefined,
      description: '',
      date: '',
      caseId: '',
      contractId: '',
      ...newData
    })
  },
  { immediate: true, deep: true }
)

// 获取案件选项
const fetchCaseOptions = async () => {
  try {
    const data = await getCaseList({ size: 100 })
    caseOptions.value = data.list
  } catch (error) {
    console.error('获取案件列表失败:', error)
  }
}

// 获取合同选项
const fetchContractOptions = async () => {
  try {
    const data = await getContractList({ size: 100 })
    contractOptions.value = data.list
  } catch (error) {
    console.error('获取合同列表失败:', error)
  }
}

// 提交表单
const handleSubmit = async () => {
  if (!formRef.value) return
  
  try {
    await formRef.value.validate()
    loading.value = true
    
    if (isEdit.value) {
      await updateFinanceRecord(form.id!, form)
      ElMessage.success('更新成功')
    } else {
      await createFinanceRecord(form)
      ElMessage.success('创建成功')
    }
    
    emit('success')
    handleClose()
  } catch (error: any) {
    ElMessage.error(error.message || '操作失败')
  } finally {
    loading.value = false
  }
}

// 关闭对话框
const handleClose = () => {
  formRef.value?.resetFields()
  emit('update:visible', false)
}

onMounted(() => {
  fetchCaseOptions()
  fetchContractOptions()
})
</script>
